package com.service;

import com.base.Constants;
import com.bean.WebsiteContent;
import com.bean.wechat.*;
import com.mapper.repository.mysql.*;
import com.utils.APIUtils;
import com.utils.BaseUtils;
import com.utils.wechat.WechatStrategyFactory;
import com.utils.wechat.WxReplyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

@Service
public class WeChatServiceImpl implements WeChatService {

    @Autowired
    private APIUtils apiUtils;

    @Autowired
    private BaseUtils baseUtils;

    @Autowired
    private WechatContentRepository wechatContentRepository;

    @Autowired
    private WebsiteContentRepository websiteContentRepository;

    @Autowired
    private WechatMsgRepository wechatMsgRepository;

    @Value("${wechat.appid}")
    //微信公众号APPID
    private String account ;

    private String resc = "请关注公众号:‘软件漫游指南’";

    //判断是事件还是消息
    @Override
    public String replyMessage(Map<String,String> map) {
        String msgType=map.get("MsgType");
        String result="";
        if(!"event".equals(msgType)){
            try {
                result=message(map);//处理消息事件
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                result = event(map);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @Autowired
    private WxReplyMessage wxReplyMessage;

    private String replyMessage(ResultInfo resultInfo){
        String getGreetingMessage = this.apiUtils.getGreetingMessage();
        if (getGreetingMessage != null && !getGreetingMessage.equals("") && resultInfo.getReturnMethod().equals("text")) {
            resultInfo.setContent(getGreetingMessage+"\n" + resultInfo.getContent());
        }
        return wxReplyMessage.replyMessage(resultInfo,resultInfo.getReturnMethod());
    }

    @Autowired
    private WechatStrategyFactory wechatStrategyFactory;

    //处理消息
    private String message(Map<String,String> map) throws IOException {
        String result="";
        ResultInfo resultInfo=new ResultInfo();
        resultInfo.setFromUserName(map.get("ToUserName"));
        resultInfo.setToUserName(map.get("FromUserName"));
        resultInfo.setCreteTime(wxReplyMessage.getUtcTime());
        String msgType=map.get("MsgType");
        if("text".equals(msgType)){//普通消息
            String content=map.get("Content");
            if(content.equals("功能")){
                wechatStrategyFactory.getResultInfo(resultInfo,null, Constants.WechatFunction);
                return replyMessage(resultInfo);

            }else
            if(content.startsWith("绑定")){
                wechatStrategyFactory.getResultInfo(resultInfo,content, Constants.WechatBind);
                return replyMessage(resultInfo);

            }else
            if(content.endsWith("的信息")||content.endsWith("的密码")){
                wechatStrategyFactory.getResultInfo(resultInfo,content, Constants.WechatLogintoken);
                return replyMessage(resultInfo);

            }else
            if(content.equals("开心一下")){
                //result = returnJoke(resultInfo,content);
                if(istyd(resultInfo)){
                    wechatStrategyFactory.getResultInfo(resultInfo,content, Constants.WechatJokes);
                }
                return replyMessage(resultInfo);

            }else
            if(content.equals("奇葩对话")){
                //result = returnJoke(resultInfo,content);
                if(istyd(resultInfo)){
                    wechatStrategyFactory.getResultInfo(resultInfo,content, Constants.WechatQpdh);
                }
                return replyMessage(resultInfo);

            }else
            if(content.equals("脑筋急转弯")){
                //result = returnJoke(resultInfo,content);
                if(istyd(resultInfo)){
                    wechatStrategyFactory.getResultInfo(resultInfo,content, Constants.WechatRiddle);
                }
                return replyMessage(resultInfo);

            }else
            if(content.equals("随机图片")){
                //result = returnJoke(resultInfo,content);
                wechatStrategyFactory.getResultInfo(resultInfo,content, Constants.WechatFreeApiTu);
                return replyMessage(resultInfo);

            }else
            if(content.equals("公众号服务")||content.startsWith("ID:")){
                wechatStrategyFactory.getResultInfo(resultInfo,content, Constants.WechatServer);
                return replyMessage(resultInfo);
            }else
           /* if(content.equals("个人系统")){
                result = returnSystem(resultInfo);
            }else*/
            if(content.startsWith("结婚：")){
                result = returnWechatMsgWedding(resultInfo,content);
            }else
            /*if(content.equals("随机音乐")){
                result = returnSjmusic(resultInfo);
            }else */
                {
                result = returnWebsiteUrl(resultInfo,content);
            }
        }
        return result;
    }

    private String event(Map<String,String> map) throws IOException {
        String result="";
        ResultInfo resultInfo=new ResultInfo();
        resultInfo.setFromUserName(map.get("ToUserName"));
        resultInfo.setToUserName(map.get("FromUserName"));
        resultInfo.setCreteTime(wxReplyMessage.getUtcTime());
        String event=map.get("Event");//unsubscribe
        if("subscribe".equals(event)){
            //如果关注的是自己的公众号，就保存关注信息，如果不是，不保存，所以要知道自己的公众号ID是多少 gh_ae6a631527da 微信公众号的原始ID
            if(resultInfo.getFromUserName().equals(account)){
                handleOwend(resultInfo,"sub");//
            }
            //result = returnSubScribe(resultInfo);

            wechatStrategyFactory.getResultInfo(resultInfo,null, Constants.WechatFunction);
            return replyMessage(resultInfo);

        }
        if("unsubscribe".equals(event)){
            if(resultInfo.getFromUserName().equals(account)){
                handleOwend(resultInfo,"unsub");
            }
            result = returnUnSubScribe(resultInfo);
        }
        return result;
    }

//    @Autowired
//    private UserInfoWxRepository userInfoWxRepository;




/*    public String returnSystem(ResultInfo resultInfo) {

        resultInfo.setReturnMethod("news");
        resultInfo.setTitle("个人信息系统");
        resultInfo.setDescription("管理个人的信息等内容,“请勿转发!!!!”“仅限个人阅读!!!”");
        resultInfo.setUrl("http://"+server+":"+port+"/?openid="+resultInfo.getToUserName());
        return replyMessage(resultInfo);
    }*/

 /*   public String returnSjmusic(ResultInfo resultInfo) {
        resultInfo.setReturnMethod("news");
        resultInfo.setTitle("随机音乐");
        resultInfo.setDescription("基于网易随机音乐API");
        resultInfo.setUrl("http://"+server+":"+port+"/music.html");
        return replyMessage(resultInfo);
    }*/


    //回复 结婚：田友达&贺成雅   返回图文。
    public String returnWechatMsgWedding(ResultInfo resultInfo,String content ) {
        String request = content.substring("结婚：".length());
        WechatMsg wechatMsg = wechatMsgRepository.findByRequest(request);
        if(wechatMsg!=null){
            resultInfo.setReturnMethod("news");
            resultInfo.setTitle(request+" 我们结婚啦！");
            resultInfo.setDescription("诚挚邀请您参加我们的婚礼，见证我们的爱情之路，共享美好时刻!");
            resultInfo.setUrl(wechatMsg.getResponse());
            resultInfo.setPicUrl(baseUtils.getBaseConfigByName("new_wedding"));
        }else{
            resultInfo.setReturnMethod("text");
            resultInfo.setContent("请求的"+content+"不存在");
        }
        return replyMessage(resultInfo);
    }

    @Autowired
    private WechatAccountRepository wechatAccountRepository;

    public String returnWebsiteUrl(ResultInfo resultInfo,String content ) {
        boolean flag = istyd(resultInfo);//判断是否为tyd   否则判断是否绑定了ID   否则判断是否还在关注
        if(flag){
            WebsiteContent websiteContent = websiteContentRepository.getWebsiteContentByName(content);
            if(websiteContent!=null){

                resultInfo.setReturnMethod("text");
                resultInfo.setContent(content+"的链接为"+websiteContent.getLink()+",若链接在微信无法打开，请复制并前往浏览器");

            }else{

                String id =UUID.randomUUID().toString();
                WechatContent wechatContent = new WechatContent() ;
                wechatContent.setId(id);
                wechatContent.setContent(content);
                wechatContent.setUserid(resultInfo.getToUserName());
                wechatContent.setCreatetime(LocalDateTime.now());
                wechatContentRepository.save(wechatContent);

                resultInfo.setReturnMethod("news");
                resultInfo.setTitle("点击查看“"+content+"”检索内容");//可可影视，
                resultInfo.setDescription("点击前往网站推荐查看");//点击进入，如打不开，请用浏览器打开
                resultInfo.setPicUrl(baseUtils.getBaseConfigByName("wechat_search_png"));
                resultInfo.setUrl(baseUtils.getWechatUrl()+"?wid="+id);
            }
        }
        return replyMessage(resultInfo);
    }

    //取消关注
    public String returnUnSubScribe(ResultInfo resultInfo) {
        //判断是否存在，如果存在就更新
        resultInfo.setReturnMethod("text");
        return replyMessage(resultInfo);
    }



    private void handleOwend(ResultInfo resultInfo,String type){
        switch (type){
            case "unsub":
                handleWechatUserInfo(resultInfo,"取消订阅","unsub");
                break;
            case "sub":
                handleWechatUserInfo(resultInfo,"已订阅","sub");
                break;
            default:
                System.out.println("其他类型");
        }


    }

    @Autowired
    private WechatUserInfoRepository wechatUserInfoRepository;

    //保存订阅的用户信息
    public void handleWechatUserInfo(ResultInfo resultInfo,String status,String type){
        WechatUserInfo wechatUserInfo = wechatUserInfoRepository.findByUserid(resultInfo.getToUserName());
        if(type.equals("sub")){
            if(wechatUserInfo!=null){
                wechatUserInfo.setStatus(status);
                wechatUserInfo.setSubtime(LocalDateTime.now());
                wechatUserInfo.setUnsubtime(null);
            }else{
                wechatUserInfo = new WechatUserInfo();
                wechatUserInfo.setId(UUID.randomUUID().toString());
                wechatUserInfo.setUserid(resultInfo.getToUserName());
                wechatUserInfo.setSubtime(LocalDateTime.now());
                wechatUserInfo.setStatus(status);
            }
        }else{
            wechatUserInfo.setStatus(status);
            wechatUserInfo.setUnsubtime(LocalDateTime.now());
        }
        wechatUserInfoRepository.save(wechatUserInfo);
    }

    //处理事件
   /* private String event(Map<String,String> map){
        String result="";
        String event=map.get("Event");
        ResultInfo resultInfo=new ResultInfo();
        resultInfo.setFromUserName(map.get("ToUserName"));
        resultInfo.setToUserName(map.get("FromUserName"));
        resultInfo.setCreteTime(wxReplyMessage.getUtcTime());
        if("CLICK".equals(event)&&map.get("EventKey")!=null){

            if("BWL".equals(map.get("EventKey"))){
                BWL(resultInfo);
            }
            if("DC".equals(map.get("EventKey"))){
                DC(resultInfo);
            }
            result=replyMessage(resultInfo);
        }

        return result;
    }*/



    //点击事件--备忘录
/*    private void BWL(ResultInfo resultInfo){
        resultInfo.setReturnMethod("news");
        resultInfo.setTitle("测试");
        resultInfo.setDescription("这个不能转发哦!!!");
        resultInfo.setUrl(natappUrl+"/memo.html?userid="+resultInfo.getToUserName());
    }*/

    //点击事件--点餐
/*    private void DC(ResultInfo resultInfo){
        resultInfo.setReturnMethod("news");
        resultInfo.setTitle("菜单");
        resultInfo.setDescription("这个不能转发哦!!!");
        resultInfo.setUrl(natappUrl+"/menu.html?userid="+resultInfo.getToUserName());
    }*/

/*    private void DD(ResultInfo resultInfo){
        resultInfo.setReturnMethod("news");
        resultInfo.setTitle("订单");
        resultInfo.setDescription("转发这个给你的初始哦!!!");
        resultInfo.setUrl(natappUrl+"/memo.html?userid="+resultInfo.getToUserName());
    }*/

    public boolean istyd(ResultInfo resultInfo){
        boolean flag =false;
        String accountId = resultInfo.getFromUserName();
        if(!accountId.equals(account)){

            //不是主体，判断是否绑定了userid   公众号添加了链接，但是没有配置ID
            WechatAccount wechatAccount = wechatAccountRepository.findByAccount(accountId);
            if(wechatAccount == null){
                //没有找到绑定的公众号ID
                resultInfo.setReturnMethod("text");
                resultInfo.setContent("很高兴您使用服务，请回复'ID:您获取到的ID'后再使用");

            }else{
                //公众号配置了ID ，但是取消了对tyd的关注
                String userid = wechatAccount.getUserid();
                WechatUserInfo wechatUserInfo = wechatUserInfoRepository.findByUserid(userid);
                if(wechatUserInfo.getStatus().equals("已订阅")){
                    flag = true;
                }else{
                    resultInfo.setReturnMethod("text");
                    resultInfo.setContent("已取关服务方，"+resc);
                }
            }

        }else{
            //公众号是tyd
            flag = true;
        }
        return flag;
    }

}
